<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="部门名称"></el-input>
				</el-form-item>
        <!--  上级部门下拉框      -->
				<el-form-item>
          <el-select v-model="filters.parentId" clearable placeholder="上级部门">
            <el-option
                v-for="item in allDept"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
				</el-form-item>
        <!--  部门经理下拉     -->
				<el-form-item>
          <el-select v-model="filters.managerId" clearable placeholder="部门经理">
            <el-option
                v-for="item in allManager"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getdept">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
<!--		:data :绑定的数据-->
<!--		v-loading: 页面css样式等东西加载之后加载加载数据-->
<!--		prop:对应的是:data绑定的对象的属性-->
<!--		label :描述-->
		<el-table :data="dept" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>

			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="100" sortable>
			</el-table-column>

			<el-table-column prop="manager.username" label="部门经理" width="100" sortable>
			</el-table-column>

			<el-table-column prop="parent.name" label="上级部门" width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			current-change:自带的事件,我当前页发生改变时,就会触发此事件-->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="5" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="操作" :visible.sync="addFormVisible"  :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="addForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
          <el-switch
              v-model="addForm.state"
              active-text="启用"
              inactive-text="禁用">
          </el-switch>
				</el-form-item>
				<el-form-item label="部门经理" prop="managerId">
          <el-select v-model="addForm.managerId" clearable placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
				</el-form-item>
        <el-form-item label="上级部门" prop="parentId">
        <el-cascader
            v-model="addForm.parentIds"
            :options="deptTree"
            :props="{ checkStrictly: true,value:'id',label:'name' }"
            clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
          managerId:'',
					name: '',
          parentId:''
				},
        deptTree:[],
        emps:[],
        allManager:[],
        allDept:[],
				dept: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
              /*required：必填 message：如果不符合规则的提示信息 blur:光标离开触发*/
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
					// sn: [
					// 	{ required: true, message: '请输入编号', trigger: 'blur' }
					// ]
				},
				//新增界面数据
				addForm: {
					name: '',
					sn: '',
          state:true,
          parentIds:[]
				}

			}
		},
		methods: {
			//性别显示转换
			//row 当前行row = user  column当前列
			formatSex: function (row, column) {
				return row.state == 1 ? '正常' : row.state == 0 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				//var 就是当前页的数据
        //alert(val)
				this.page = val;
				this.getdept();
			},
			//获取部门列表
			getdept() {
				//封装的数据
				let para = {
					//page 就是当前页
					page: this.page,
					//这个是高级查询的条件
					name: this.filters.name,
					parentId : this.filters.parentId,
          managerId : this.filters.managerId
				};
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/dept/findPage",para).then((res) => {
					// console.log("后端发送过来的分页数据:"+JSON.stringify(res));
          console.log(res)
					//
					this.total = res.data.total;
					//
					this.dept = res.data.list;
					//关闭进度条
					this.listLoading = false;
					//NProgress.done();
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/dept/"+row.id).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getdept();
					});
				}).catch(() => {

				});
			},

			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					name: '',
					sn: '',
          state:true
				};
			},

      handleEdit(row){
        console.log(row)
        //弹出对话框
        this.addFormVisible = true;
        //回显

        this.addForm = Object.assign({},row);
        // 1 : !1 :false !!1:true
        this.addForm.state = !!row.state;
        //this.addForm.parentIds = [3,7]

        //alert(row.dirPath);//    /3/7/10
        let paths = []
        if (row.dirPath){
          var arrs = row.dirPath.split("/");
          console.log(arrs)
          let path =  arrs.slice(1,arrs.length-1);
          //console.log(path.map(Number))
          this.addForm.parentIds = path.map(Number);
        }
      },

			//新增
			addSubmit: function () {
				//$refs调用js 原生dom元素
				//validate
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							//这里才是我们处理数据的地方
							this.addLoading = true;
							//Object.assign 复制对象的
              this.addForm.state =  this.addForm.state?1:0;
              let para = Object.assign({}, this.addForm);

              console.log(para)

							this.$http.post("/dept",para).then((res) => {
								this.addLoading = false;
								//elementUi的提示弹框
								this.$message({
									message: res.data.message,
									type: res.data.success?'success':'error'
								});
								//重新set数据
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getdept();
							});
						});
					}
				});
			},
			//复选勾选框的方法
			selsChange: function (sels) {
        console.log(sels)
				this.sels = sels;// [{id:1,name:"开发部"}{id:2,name:"开发部2"}]
			},
			//批量删除
			batchRemove: function () {
        //map抽取id值
				var ids = this.sels.map(item => item.id); //ids :[1,2]
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids }; //{ids:[1,2]}
					this.$http.post("/dept/batchRemove",para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getdept();
					});
				}).catch(() => {

				});
			},
      getAllDept(){
        this.$http.get("/dept").then(res=>{
          console.log(res)
          //获取数据
          this.allDept = res.data.data;
        })
      },
      findManagers(){
        this.$http.get("/emp/findManagers").then(res=>{
          console.log(res)
          //获取数据
          this.allManager = res.data.data;
        })
      },
      findEmps(){
        this.$http.get("/emp").then(res=>{
          console.log(res)
          //获取数据
          this.emps = res.data.data;
        })
      },
      findDeptTree(){
        this.$http.get("/dept/deptTree").then(res=>{
          console.log(res)
          //获取数据
          this.deptTree = res.data.data;
        })
      }
		},
		//就是页面已加载完成就会去触发这个mounted
		mounted() {
			this.getdept();
      //获取所有的部门，所有的部门都有可能是上级部门
      this.getAllDept();
      //获取所有的经理
      this.findManagers();
      //获取所有员工
      this.findEmps();
      //获取无限极树
      this.findDeptTree();
		}
	}

</script>

<style scoped>

</style>
